<?php

require_once("cfg/cfg.php");
require_once("lib/mysql.class.php");
require_once("lib/timer.class.php");
require_once("lib/logger.class.php");


class Transfer
{
    public function __construct()
    {
        $this->init();
    }
    
    private function init()
    {
        MySQL::$url = DBURL;
        $this->db = MySQL::getInstance();
        Logger::$log_file = USR_LOG_FILE;
    }
    
    private function prepare_phone($phone)
    {
        return str_replace("+", "", $phone);
    }
    
    // создание перевода
    public function make($phone1, $phone2, $sum)
    {
        $dt = date("Y-m-d H:i:s");
        $sql = "INSERT INTO transfers(phone1, phone2, money_sum, dt1) VALUES(%s, %s, %s, %s)";
		$params = array(
			$this->db->escape($this->prepare_phone($phone1)),
			$this->db->escape($this->prepare_phone($phone2)),
			$this->db->escape($sum),
			$this->db->escape($dt)
			);
		$sql = vsprintf($sql, $params);
        $this->show2($sql);
        
        $res = $this->db->query($sql);
        return $this->db->insert_id();
    }
    
    // проверка существования перевода у получателя
    public function find($phone1, $state='N', $phone2=null)
    {
        $add_where = "";
        $add_where .= is_null($state)  ? "" : " AND state='".$state."'";
        $add_where .= is_null($phone2) ? "" : " AND phone2='".$this->prepare_phone($phone2)."'";
        
        $sql = "SELECT id, phone1, phone2, money_sum, state, dt1, dt2 FROM transfers WHERE phone2 = ".$this->prepare_phone($phone1).$add_where;
        $res = $this->db->query($sql);
        $this->show2($sql);
        if($this->db->num_rows($res) === 0) return null;
        $row = $this->db->fetch_assoc($res);
        return $row;
    }
    

    // получение информации о переводе
    public function get2($transfer_id)
    {
        $sql = "SELECT id, phone1, phone2, money_sum, state, dt1, dt2 FROM transfers WHERE id = ".$transfer_id;
        $res = $this->db->query($sql);
        $this->show2($sql);
        if($this->db->num_rows($res) === 0) return null;
        $row = $this->db->fetch_assoc($res);
        return $row;
    }
    
    // выдача перевода
    public function give($transfer_id)
    {
        $this->change_state($transfer_id, 'Y');
    }
    
    // отмена перевода
    public function cancel($transfer_id)
    {
        $this->change_state($transfer_id, 'X');
    }
    
    private function change_state($transfer_id, $state)
    {
        $sql = "UPDATE transfers SET state = '".$state."' WHERE id = ".$transfer_id;
        $this->show2($sql);
        $this->db->query($sql);
    }
    
    private function show2($msg)
    {
    	Logger::Write("SQL", $msg);
        //echo $msg."\n";
    }
    
    private $db = null;
    
}
